package com.haoxuer.discover.user.rest.filters;

import com.haoxuer.discover.filter.common.Filter;
import com.haoxuer.discover.filter.common.FilterChain;
import com.haoxuer.discover.filter.common.HandlerRequest;
import com.haoxuer.discover.filter.common.HandlerResponse;
import com.haoxuer.discover.user.data.dao.UserInfoDao;
import com.haoxuer.discover.user.data.entity.UserInfo;
import com.haoxuer.discover.user.service.UserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Scope("prototype")
@Component
public class CheckUserTokenFilter implements Filter {

  @Autowired
  private UserTokenService tokenService;

  @Autowired
  private UserInfoDao userInfoDao;

  @Override
  public void doFilter(HandlerRequest request, HandlerResponse response, FilterChain filterChain) {
    String userToken = request.getParameter("userToken");
    Long member = tokenService.user(userToken);
    if (member == null) {
      response.setCode(-1);
      response.setMsg("用户令牌无效");
      return;
    }
    UserInfo user = userInfoDao.findById(member);
    if (user == null) {
      response.setMsg("该用户信息不存在");
      response.setCode(-6);
      return;
    }
    request.setAttribute("user", user);
    filterChain.doFilter(request, response);
  }
}
